package com.leoman.post.controller;

import com.leoman.category.entity.Category;
import com.leoman.category.service.CategoryService;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.post.entity.*;
import com.leoman.post.service.*;
import com.leoman.post.service.impl.PostBaseServiceImpl;
import com.leoman.sensitivewords.service.SensitiveWordsService;
import com.leoman.userapi.service.UserIntegralService;
import com.leoman.userchange.entity.UserChange;
import com.leoman.utils.FileUtil;
import com.leoman.utils.ImageUtil;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 帖子controller
 * Created by 蔡琦 on 2016/7/13 0013.
 */
@Controller
@RequestMapping(value = "admin/post")
public class PostController extends GenericEntityController<PostBase, PostBase, PostBaseServiceImpl> {


    @Autowired
    private PostBaseService postBaseService;

    @Autowired
    private ZbPostInfoService zbPostInfoService;

    @Autowired
    private TpPostSubService tpPostSubService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private PostImageService postImageService;

    @Autowired
    private SensitiveWordsService sensitiveWordsService;

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private UserChangeService userChangeService;

    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "post/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     String name,
                     Long category,
                     Integer status,
                     Integer essence,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {

            int pageNum = getPageNum(start, length);

            Page<PostBase> page = postBaseService.findPage(name, category, status, essence, null, pageNum, length);
            List<PostComment> postCommentList;
            List<UserChange> userChangeList;
            for (PostBase postBase : page.getContent()) {

                // 查询贴子的评论数
                postCommentList = postCommentService.findByPostId(postBase.getId());
                postBase.setComment(postCommentList != null ? postCommentList.size() : 0);

                // 查询帖子点赞数
                userChangeList = userChangeService.findByPostId(postBase.getId());
                postBase.setPraise(userChangeList != null ? userChangeList.size() : 0);

                if (postBase.getType() == 1) {
                    // 修改直播贴状态，如果开始时间小于当前系统时间则“正在进行”
                    if (postBase.getStartDate() <= System.currentTimeMillis() && postBase.getStatus() != 2) {
                        postBase.setStatus(1);
                    }
                }
                if (postBase.getType() == 2) {
                    // 修改投票贴状态，如果截止时间小于当前系统时间则“已结束”
                    if (postBase.getEndDate() < System.currentTimeMillis()) {
                        postBase.setStatus(2);
                    } else {
                        postBase.setStatus(1);
                    }
                }
                postBaseService.update(postBase);
                if (StringUtils.isNotEmpty(postBase.getAvater())) {
                    postBase.setAvater(ImageUtil.clearUploadUrl(postBase.getAvater()));
                }
            }

            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 上传缓存图片
     */
    @RequestMapping("/addTempImage")
    @ResponseBody
    public PostImage addTempImage(MultipartRequest multipartRequest, Long zbPostId) {
        PostImage image = new PostImage();

        try {
            MultipartFile multipartFile = multipartRequest.getFile("tempImage");

            // 验证图片格式
            String originalFileName = multipartFile.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".jpg");
            list.add(".gif");
            list.add(".jpeg");
            list.add(".png");
            list.add(".bmp");

            if (!list.contains(fileType)) {
                return image;
            }

            FileBo fileBo = FileUtil.save(multipartFile, true);
            image.setUrl(fileBo.getPath());
            image.setType(1);
            image.setSuolue(fileBo.getSuoluePath());
            if (zbPostId != null) {
                image.setPostId(zbPostId);
            }

            postImageService.save(image);
            image.setUrl(ImageUtil.clearUploadUrl(fileBo.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return image;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    public String add() {

        return "post/add";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit")
    public String edit(Long postId, Model model) {

        PostBase postBase = postBaseService.queryByPK(postId);
        if (StringUtils.isNotEmpty(postBase.getContent())) {
            postBase.setContent(postBase.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));
        }
        if (StringUtils.isNotEmpty(postBase.getAvater())) {
            postBase.setAvater(ImageUtil.clearUploadUrl(postBase.getAvater()));
        }
        model.addAttribute("postBase", postBase);
        if (postBase.getType().equals(Constant.POST_TYPE_000)) {
            return "post/ptPostAdd";
        } else if (postBase.getType().equals(Constant.POST_TYPE_001)) {

            // 查询直播贴
            model.addAttribute("zbPostInfoList", findAndJoinZBPostImg(postId));
            return "post/zbPostAdd";
        } else if (postBase.getType().equals(Constant.POST_TYPE_002)) {

            // 查询投票贴
            List<TpPostSub> tpPostSubList = tpPostSubService.findByPostId(postId);
            for (TpPostSub tpPostSub : tpPostSubList) {
                if (StringUtils.isNotEmpty(tpPostSub.getCover())) {
                    tpPostSub.setCover(ImageUtil.clearUploadUrl(tpPostSub.getCover()));
                }
            }
            model.addAttribute("tpPostSubList", tpPostSubList);
            return "post/tpPostAdd";
        }
        return null;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail")
    public String detail(Long postId, Model model) {

        PostBase postBase = postBaseService.queryByPK(postId);
        if (StringUtils.isNotEmpty(postBase.getContent())) {
            postBase.setContent(postBase.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));
        }
        if (StringUtils.isNotEmpty(postBase.getAvater())) {
            postBase.setAvater(ImageUtil.clearUploadUrl(postBase.getAvater()));
        }
        model.addAttribute("postBase", postBase);
        if (postBase.getType().equals(Constant.POST_TYPE_000)) {

            return "post/ptPostDetail";
        } else if (postBase.getType().equals(Constant.POST_TYPE_001)) {

            // 查询直播贴
            model.addAttribute("zbPostInfoList", findAndJoinZBPostImg(postId));
            return "post/zbPostDetail";
        } else if (postBase.getType().equals(Constant.POST_TYPE_002)) {

            // 查询投票贴
            List<TpPostSub> tpPostSubList = tpPostSubService.findByPostId(postId);
            for (TpPostSub tpPostSub : tpPostSubList) {
                if (StringUtils.isNotEmpty(tpPostSub.getCover())) {
                    tpPostSub.setCover(ImageUtil.clearUploadUrl(tpPostSub.getCover()));
                }
            }
            model.addAttribute("tpPostSubList", tpPostSubList);
            return "post/tpPostDetail";
        }

        return null;
    }

    /**
     * 设置、取消精华
     */
    @RequestMapping(value = "/isEssence")
    @ResponseBody
    public Integer isEssence(Long postId, Integer essence) {

        PostBase postBase = postBaseService.queryByPK(postId);
        postBase.setEssence(essence);

        if (essence == 1) {
            userIntegralService.changeCoin(postBase.getUserInfo(), "帖子被加精华获得5馒头", 5);
        }

        postBaseService.update(postBase);

        return 1;
    }

    /**
     * 设置、取消置顶
     */
    @RequestMapping(value = "/isStick")
    @ResponseBody
    public Integer isStick(Long postId, Integer stick) {

        PostBase postBase = postBaseService.queryByPK(postId);
        postBase.setStick(stick);

        if (stick == 1) {
            userIntegralService.changeCoin(postBase.getUserInfo(), "帖子被置顶获得5馒头", 5);
        }

        postBaseService.update(postBase);

        return 1;
    }

    /**
     * 删除直播贴图片
     */
    @RequestMapping(value = "/deleteImage")
    @ResponseBody
    public Integer deleteImage(Long imageId) {

        PostImage postImage = postImageService.queryByPK(imageId);
        postImageService.delete(postImage);

        return 1;
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Integer save(Long postId,
                        Long creatorList,
                        String name,
                        Long typeList,
                        Integer type,
                        String content,
                        String startDate,
                        String description,
                        String endDate,
                        String[] tpSub,
                        String[] tpSubs,
                        String isActivity,
                        MultipartRequest multipartRequest) throws IOException, ParseException {

        // 过滤敏感字符
        name = sensitiveWordsService.replaceWord(name);
        content = sensitiveWordsService.replaceWord(content);

        postBaseService.saveAll(postId, creatorList, name, typeList, type, content, startDate, description, endDate, tpSub, tpSubs, isActivity, multipartRequest);
        return 1;
    }

    /**
     * 添加直播
     */
    @RequestMapping(value = "/addZB")
    @ResponseBody
    public Integer addZB(HttpServletRequest request,
                         Long postId,
                         Long creatorId,
                         String tempAddImageIds1,
                         String tempDelImageIds,
                         Integer status) throws UnsupportedEncodingException {

        postBaseService.addZB(request, postId, creatorId, tempAddImageIds1, tempDelImageIds, status);

        return 1;
    }

    /**
     * 保存修改后的直播贴
     */
    @RequestMapping(value = "/saveZB")
    @ResponseBody
    public Integer saveZB(HttpServletRequest request,
                          Long postId,
                          Long creatorList,
                          String name,
                          Long typeList,
                          Integer type,
                          String startDate,
                          String[] description,
                          String tempDelImageIds,
                          MultipartRequest multipartRequest) throws IOException, ParseException {

        postBaseService.saveZB(request, postId, creatorList, name, typeList, type, startDate, description, tempDelImageIds, multipartRequest);
        return 1;
    }

    /**
     * 批量删除帖子
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @ResponseBody
    public Integer deleteBatch(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        for (Long id : arrayId) {
            postBaseService.deletePost(id);
        }
        return 1;
    }

    /**
     * 单个删除帖子
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Integer delete(Long postId) {

        return postBaseService.deletePost(postId);
    }

    /**
     * 删除投票对象
     */
    @RequestMapping(value = "/deleteTpSub")
    @ResponseBody
    public Integer deleteTpSub(Long postId) {

        TpPostSub tpPostSub = tpPostSubService.queryByPK(postId);
        tpPostSubService.delete(tpPostSub);

        return 1;
    }

    /**
     * 查询帖子分类列表
     */
    @RequestMapping(value = "/categoryList")
    @ResponseBody
    public List<Category> categoryList() {

        return categoryService.findType(Constant.CATEGORY_TYPE_001);
    }

    public List<ZbPostInfo> findAndJoinZBPostImg(Long postId) {
        List<ZbPostInfo> zbPostInfoList = zbPostInfoService.findByPostId(postId);
        for (ZbPostInfo zbPostInfo : zbPostInfoList) {
            zbPostInfo.setImageList(postImageService.findList(zbPostInfo.getId(), 1));
            for (PostImage postImage : zbPostInfo.getImageList()) {
                if (StringUtils.isNotEmpty(postImage.getUrl())) {
                    postImage.setUrl(ImageUtil.clearUploadUrl(postImage.getUrl()));
                }
            }
        }

        return zbPostInfoList;
    }

    /**
     * 投票统计
     */
    @RequestMapping(value = "/infoData")
    public String infoData(ModelMap model, Long postId) {
        model.addAttribute("postId", postId);
        return "post/postTpSubData";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/infoData/list")
    public void dataList(HttpServletResponse response,
                         Long postId,
                         Integer draw,
                         Integer start,
                         Integer length) {
        try {
            int pageNum = getPageNum(start, length);
            Page<PostTpSubData> page = tpPostSubService.pageByParams(postId, pageNum, length);
            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }
}
